package cn.com.joycode.nimble.core.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Max Woods
 */

public class QueryStrUtil {

    public static String build(String json) {
        JSONObject jsonObject = JSONUtil.parseObj(json);
        TreeMap<String, Object> params = new TreeMap<>();
        jsonObject.entrySet().stream().forEach(entry -> {
            params.put(entry.getKey(), entry.getValue());
        });
        StringBuilder sb = new StringBuilder();
        params.forEach((key, value) -> {
            sb.append(key).append("=").append(value).append("&");
        });
        return StrUtil.removeSuffix(sb.toString(), "&");
    }

    public static String build(Object object) {
        TreeMap<String, Object> treeMap = ObjectMapperUtil.convertValue(object, new TypeReference<TreeMap<String, Object>>() {
        });
        StringBuilder sb = new StringBuilder();
        treeMap.forEach((key, value) -> {
            sb.append(key).append("=").append(value).append("&");
        });
        return StrUtil.removeSuffix(sb.toString(), "&");
    }

    public static String build(Map<String, Object> map) {
        StringBuilder sb = new StringBuilder();
        map.forEach((key, value) -> {
            sb.append(key).append("=").append(value).append("&");
        });
        return StrUtil.removeSuffix(sb.toString(), "&");
    }

    public static Map<String, String> getParamsMap(String queryString) {
        Map<String, String> result = new HashMap<>();
        StrUtil.split(queryString, "&").forEach(keyValue -> {
            List<String> strs = StrUtil.split(keyValue, "=");
            if (strs.size() > 1) {
                String key = strs.get(0);
                String value = strs.get(0);
                while (StrUtil.contains(value, '%')) {
                    value = URLUtil.decode(value);
                }
                result.put(key, value);
            } else {
                result.put(strs.get(0), strs.get(0));
            }
        });
        return result;
    }
}
